package com.hsurosy.domain.strategy.service.rule.tree.impl;

import com.hsurosy.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.hsurosy.domain.strategy.service.rule.tree.ILogicTreeNode;
import com.hsurosy.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import com.hsurosy.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Author Hsu琛君珩
 * @Date 2024-10-19 15:26
 * @Description 兜底奖励节点逻辑处理类
 * @Version: v1.0.0
 */
@Slf4j
@Component("rule_luck_award")
public class RuleLuckAwardLogicTreeNode implements ILogicTreeNode {

    /**
     * 执行规则树的兜底奖品处理逻辑。
     *
     * @param userId 用户ID
     * @param strategyId 抽奖策略ID
     * @param awardId 当前抽中的奖品ID
     * @param ruleValue 规则值，格式为 "奖品ID:奖品规则" 的字符串
     * @return TreeActionEntity 包含规则的检查结果和最终的奖品数据
     */
    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue) {
        log.info("规则过滤-兜底奖品 userId:{} strategyId:{} awardId:{} ruleValue:{}", userId, strategyId, awardId, ruleValue);

        // 1. 解析规则值，期望格式为 "奖品ID:奖品规则"
        String[] split = ruleValue.split(Constants.COLON);
        if (split.length == 0) {
            log.error("规则过滤-兜底奖品，兜底奖品未配置警告 userId:{} strategyId:{} awardId:{} ", userId, strategyId, awardId);
            throw new RuntimeException("兜底奖品未配置 " + ruleValue);
        }

        // 2. 兜底奖励配置，解析奖品ID和奖品规则
        Integer luckAwardId = Integer.valueOf(split[0]);  // 兜底奖品ID
        String awardRuleValue = split.length > 1 ? split[1] : "";  // 奖品规则，如果存在则解析，否则为空

        log.info("规则过滤-兜底奖品 userId:{} strategyId:{} awardId:{} awardRuleValue:{}", userId, strategyId, awardId, awardRuleValue);

        // 3. 返回兜底奖品的奖品ID和规则，接管抽奖流程
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)  // 接管流程
                .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                        .awardId(awardId)  // 兜底奖品ID
                        .awardRuleValue(awardRuleValue)  // 奖品规则
                        .build())
                .build();
    }

}
